package com.fable.sp.core.util;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * .
 *
 * @author stormning on 16/8/17.
 */
public class CollectionUtils extends org.springframework.util.CollectionUtils {

    public static <K, S> Map<K, S> toMap(Collection<S> collection, Function<S, K> keyFunction) {
        Map<K, S> result = Maps.newHashMap();
        if (!isEmpty(collection)) {
            for (S s : collection) {
                if (s != null) {
                    result.put(keyFunction.apply(s), s);
                }
            }
        }
        return result;
    }

    public static <K, S> Map<K, List<S>> toMapList(Collection<S> collection, Function<S, K> keyFunction) {
        Map<K, List<S>> result = Maps.newHashMap();
        if (!isEmpty(collection)) {
            for (S s : collection) {
                if (s != null) {
                    K key = keyFunction.apply(s);
                    List<S> cs = result.get(key);
                    if (cs == null) {
                        cs = Lists.newArrayList();
                        result.put(key, cs);
                    }
                    cs.add(s);
                }
            }
        }
        return result;
    }
}
